/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManagedBeans;

import Utilitaires.PropertiesReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import org.primefaces.model.mindmap.DefaultMindmapNode;
import org.primefaces.model.mindmap.MindmapNode;

/**
 *
 * @author michachel
 */
public class MindMapManagedBean {

    private MindmapNode root;  
      
    private MindmapNode selectedNode;  
    
    private int id;
    private String title;
    private String thematic;
    private String texte;
    
    private Properties properties;
    
    private ThreadPoolExecutor mExecutor;
      
    public MindMapManagedBean() throws MalformedURLException, IOException, JSONException 
    {  
        mExecutor = new ThreadPoolExecutor(4, 4, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(30));
        
        properties = PropertiesReader.getProperties();
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/node/t/France");
        HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
        connexion.setDoOutput(true);
        connexion.setRequestMethod("GET");
        
        try
        {
            String result = ""; 
            String line = "";

            BufferedReader rd = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
            while ((line = rd.readLine()) != null) {
                result += line;
            }
            rd.close();
        
            JSONObject json = new JSONObject(result);
            
            JSONArray tableau = (JSONArray) json.get("contents");
            JSONObject unObjet = (JSONObject) tableau.get(0);
            this.texte = unObjet.getString("text");
            
            for (Iterator it = json.keys(); it.hasNext();) 
            {
                String cle = (String)it.next();
                
                System.out.println(cle);
                
                if (cle.equalsIgnoreCase("id"))
                {
                    this.id = Integer.parseInt(json.get(cle).toString());
                }
                
                if (cle.equalsIgnoreCase("title"))
                {
                    this.title = json.get(cle).toString();
                }
                
                if (cle.equalsIgnoreCase("thematic"))
                {
                    this.thematic = json.get(cle).toString();
                }
            }
            
            System.out.println("Id : "+this.id);
        }
        catch (Exception e)
        {
            
        }
        
        root = new DefaultMindmapNode(this.title, this.thematic, "FFCC00", false);  
        this.selectedNode = root;
        
        url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/node/linked/"+this.id);
        connexion = (HttpURLConnection) url.openConnection();
        connexion.setDoOutput(true);
        connexion.setRequestMethod("GET");
        
        
        try
        {
            String result = ""; 
            String line = "";

            BufferedReader rd = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
            while ((line = rd.readLine()) != null) {
                result += line;
            }
            rd.close();
        
            JSONArray json = new JSONArray(result);
            
            for (int i = 0; i < json.length(); i++)
            {
                JSONObject objet = (JSONObject) json.get(i);
                int linked = Integer.parseInt(objet.get("target").toString());
                
                mExecutor.execute(getNetworkRequest("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/node/"+linked));
                
                /*url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/node/"+linked);
                connexion = (HttpURLConnection) url.openConnection();
                connexion.setDoOutput(true);
                connexion.setRequestMethod("GET");
                
                result = ""; 
                line = "";

                rd = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
                while ((line = rd.readLine()) != null) {
                    result += line;
                }
                rd.close();

                JSONObject object = new JSONObject(result);
                
                MindmapNode node = new DefaultMindmapNode(object.getString("title"), object.getString("thematic"), "6e9ebf", true);  
                root.addNode(node);*/
                synchronized(mutex) {
                    ++count;
                }
            }
            while (count > 0) {
                Thread.sleep(350);
            }
            System.out.println("End of constructor ...");
        }
        catch (Exception e)
        { 
            System.out.println(connexion.getResponseCode());
        }
    }  
  
    public MindmapNode getRoot() {  
        return root;  
    }  
  
    public MindmapNode getSelectedNode() {  
        return selectedNode;  
    }  
    public void setSelectedNode(MindmapNode selectedNode) {  
        this.selectedNode = selectedNode;  
    }  
  
    public void onNodeSelect(SelectEvent event) {  
        MindmapNode node = (MindmapNode) event.getObject();  
        this.selectedNode = node;
          
        //populate if not already loaded  
        if(node.getChildren().isEmpty()) {  
            Object label = node.getLabel();  
  
            if(label.equals("NS(s)")) {  
                for(int i = 0; i < 25; i++) {  
                    node.addNode(new DefaultMindmapNode("ns" + i + ".google.com", "Namespace " + i + " of Google", "82c542"));  
                }  
            }  
            else if(label.equals("IPs")) {  
                for(int i = 0; i < 18; i++) {  
                    node.addNode(new DefaultMindmapNode("1.1.1."  + i, "IP Number: 1.1.1." + i, "fce24f"));  
                }   
  
            }  
            else if(label.equals("Malware")) {  
                for(int i = 0; i < 18; i++) {  
                    String random = UUID.randomUUID().toString();  
                    node.addNode(new DefaultMindmapNode("Malware-"  + random, "Malicious Software: " + random, "3399ff", false));  
                }  
            }  
        }  
          
    }
    
    private static final Object mutex = new Object();
    private int count;
    
    private Runnable getNetworkRequest(final String urlS) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(urlS);
                    HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
                    connexion.setDoOutput(true);
                    connexion.setRequestMethod("GET");
                    String result = ""; 
                    String line = "";

                    BufferedReader rd = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
                    while ((line = rd.readLine()) != null) {
                        result += line;
                    }
                    rd.close();

                    JSONObject object = new JSONObject(result);

                    MindmapNode node = new DefaultMindmapNode(object.getString("title"), object.getString("thematic"), "6e9ebf", true);  
                    synchronized (mutex) {
                        System.out.println("Adding node to root ...");
                        --count;
                        root.addNode(node);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
    
    public void setRoot() {
        
    }
      
    public void onNodeDblselect(SelectEvent event) {  
        this.selectedNode = (MindmapNode) event.getObject();          
    }  
    
    // Remplissage des différents attributs à partir d'un JSON paramètre
    // envoyé par le serveur
    public void populateFromJSON(JSONObject json)
    {
        
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getThematic() {
        return thematic;
    }

    public void setThematic(String thematic) {
        this.thematic = thematic;
    }

    public String getTexte() {
        return texte;
    }

    public void setTexte(String texte) {
        this.texte = texte;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    
    
}
